package mlz.c_try;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    JDK7以前的资源释放
 */
public class TryCatchDemo01 {
    @Test
    public void test01(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.把文件图片读出来
            /*FileInputStream */fis = new FileInputStream("a.png");
            //2.写入新文件
            /*FileOutputStream */fos = new FileOutputStream("a_bak.png");

            //手动制造异常
            System.out.println(10 / 0 );

            //创建一个字节数组,负责转移字节数据
            byte[] bs = new byte[1024];
            //定义一个变量 用于记住每次读取了多少个字节
            int len;
            //3.完成文件的复制
            while((len = fis.read(bs)) != -1){
                //把文件内容依次写入到新文件中
                fos.write(bs,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            try {
                if (fis != null) fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
